using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana.HTN
{
    public sealed class HTN_Method : HTN_Task
    {
        private List<HTN_Task> tasks = new List<HTN_Task>();
        private HTN_PlanRunner planRunner;
        
        private bool MakePlan(HTN_Task task, ref List<HTN_PrimitiveTask> plan)
        {
            if (task.GetType().IsAssignableFrom(typeof(HTN_PrimitiveTask)))
            {
                if (!task.CheckPreCondition()) return false;
                plan.Add(task as HTN_PrimitiveTask);
            }
            else if (task is HTN_CompoundTask mTask)
            {
                if (mTask.TryFindPlan(out var nextPlan))
                {
                    plan.AddRange(nextPlan);
                }
            }

            return true;
        }
        
        public bool TryFindPlan(out List<HTN_PrimitiveTask> plan)
        {
            plan = new List<HTN_PrimitiveTask>();
            
            if (!CheckPreCondition()) return false;
            
            foreach (var task in tasks)
            {
                if (!MakePlan(task, ref plan)) return false;
            }

            return true;
        }

        public override HTNTaskStatus Execute()
        {
            return HTNTaskStatus.Success;
        }
    }
}